/* eslint-disable no-console */
import { BASE_LIST } from '@/config/api-constants';
import type { IObject } from '@/types/customs';
import { API_EVENTS } from './events';

const contentTypeParams = {
  json: 'application/json; charset=utf-8',
  form: 'application/x-www-form-urlencoded',
  formData: 'multipart/form-data',
};

interface Options {
  contentType?: 'json' | 'form' | 'formData'
  requestType: 'app' | 'login' | ''
}

/** 实现容错，确保地址前缀是正确的 */
function handleUrl(url: string) {
  const result = String(url).trim();
  if (result.startsWith('/') || result.startsWith('http')) {
    return url;
  }
  else {
    return `/${url}`;
  }
}

const httpInterceptor = {
  invoke(options: Partial<UniNamespace.RequestOptions & Options & IObject>) {
    const BASE_CONFIG = BASE_LIST[options.requestType || 'app'] as IObject;

    let origin = ''
    if (!options.url?.startsWith('http') && !options.url?.startsWith('https')) {
      origin = BASE_CONFIG.base;
    }

    options.url = `${origin}${handleUrl(options.url as string)}`;
    options._from = origin;
    options.header = {
      ...BASE_CONFIG.headers,
      ...(options?.header || {}),
    };
    options.timeout = 10 * 1000; // 请求超时时间

    if (options.contentType) {
      options.header['Content-type'] = contentTypeParams[options.contentType];
    }

    const token = uni.getStorageSync('token')
    if (
      token
      && BASE_CONFIG.tokenKey
      && !options.header[BASE_CONFIG.tokenKey]
    ) {
      /// options.header["Authorization"] = `Bearer ${token}`;
      options.header[BASE_CONFIG.tokenKey] = `${token}`;
    }

    // 删除描述属性
    // delete options.desc
  },
};

uni.addInterceptor('request', httpInterceptor);

export function http({
  desc,
  ...options
}: Partial<UniNamespace.RequestOptions & IObject>) {
  return new Promise<any>((resolve, reject) => {
    const _desc = desc || ''
    uni.request({
      ...options,
      success: (res) => {
        // console.log("HTTP-params: ", options.data || {});

        if (import.meta.env.DEV) {
          console.log(
            `%cHTTP-Success：%c${_desc}`,
            'background: #00cc09; color: #fff; border-radius: 3px 0 0 3px;padding:2px 8px',
            'background: #1475B2; color: #fff; border-radius: 0 3px 3px 0;padding:2px 8px',
            res,
          );
        }

        const data = res.data as HttpResult.ResponseData<unknown>;

        if (data?.rescode === 202) {
          uni.$emit(API_EVENTS.EVENT_202_TOKEN_EXPIRED, data); // 临时屏蔽，
          return reject(res.data);
        }

        if (data?.rescode === 201) {
          uni.$emit(API_EVENTS.EVENT_201_FAIL, data);
          return reject(res.data);
        }

        resolve(res.data);
      },

      fail: (err) => {
        if (import.meta.env.DEV) {
          console.log(
            `%cHTTP-Error：%c${_desc}`,
            'background: rgb(233, 51, 35); color: #fff; border-radius: 3px 0 0 3px;padding:2px 5px',
            'background: #1475B2; color: #fff; border-radius: 0 3px 3px 0;padding:2px 5px',
            err,
          );
        }

        uni.showToast({
          title: '网络错误',
          icon: 'error',
          mask: true,
        });
        reject(err);
      },
    } as UniNamespace.RequestOptions);
  })
}
